extends Control

var plane_array = [preload("res://textures/Planes/planeBlue1.png"), preload("res://textures/Planes/planeGreen1.png"), preload("res://textures/Planes/planeRed1.png"), preload("res://textures/Planes/planeYellow1.png")]
const YELLOW_CROSS = preload("res://textures/UI/yellow_cross.png")
const RED_CROSS = preload("res://textures/UI/red_cross.png")

func _ready():
	show_data()
	pass

func _on_texture_button_pressed():
	queue_free()
	pass # Replace with function body.
	
func show_data():
	delete_boxes()
	var data = Global.rank_data["players_score"]
	for i in range(0,data.size()):
		var h_box = HBoxContainer.new()
		var label_no = Label.new()
		var player_container = PanelContainer.new()
		var label_total_score = Label.new()
		var label_gold_stars = Label.new()
		var label_silver_stars = Label.new()
		var label_bronze_stars = Label.new()
		var label_use_time = Label.new()
		var label_update_time = Label.new()
		var button_delete = TextureButton.new()
		label_no.set_text(str(i+1))
		var style_box_texture = StyleBoxTexture.new()
		style_box_texture.set_texture(plane_array[data[i]["plane_type"]])
		player_container.add_theme_stylebox_override("panel",style_box_texture)
		player_container.custom_minimum_size = Vector2(30,25)
		label_total_score.set_text(str(data[i]["score"]))
		label_gold_stars.set_text(str(data[i]["star_counts"][0]))
		label_silver_stars.set_text(str(data[i]["star_counts"][1]))
		label_bronze_stars.set_text(str(data[i]["star_counts"][2]))
		label_use_time.set_text(str(data[i]["use_time"]))
		label_update_time.set_text(str(data[i]["time"]))
		button_delete.set_texture_normal(YELLOW_CROSS)
		button_delete.set_texture_hover(RED_CROSS)
		button_delete.button_down.connect(_on_button_pressed.bind(i))
		h_box.add_child(label_no)
		h_box.add_child(player_container)
		h_box.add_child(label_total_score)
		h_box.add_child(label_gold_stars)
		h_box.add_child(label_silver_stars)
		h_box.add_child(label_bronze_stars)
		h_box.add_child(label_use_time)
		h_box.add_child(label_update_time)
		h_box.add_child(button_delete)
		#h_box.add_theme_constant_override("separation",35)
		h_box.add_to_group("rank_list_boxes")
		for child in h_box.get_children():
			if child.is_class("Label"):
				child.custom_minimum_size.x = 60
				child.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
		$VBoxContainer.add_child(h_box)

func delete_boxes():
	for box in get_tree().get_nodes_in_group("rank_list_boxes"):
		box.queue_free()

func _on_button_pressed(index:int):
	Global.rank_data["players_score"].remove_at(index)
	get_tree().get_nodes_in_group("rank_list_boxes")[index].queue_free()
	var rank_data_file = FileAccess.open(Global.rank_data_url,FileAccess.WRITE)
	rank_data_file.store_line(JSON.stringify(Global.rank_data))
	rank_data_file.close()
	show_data()
